import os

# 加密密钥和头部定义
ENC_KEY = [0x3A, 0x57, 0xB1, 0xC4, 0x2D, 0x9E, 0x11, 0x7F, 0x63, 0xA0]
HEADER = b"MCFG1"

def xor_decrypt(data, key):
    """对数据进行 XOR 解密"""
    return bytes(data[i] ^ key[i % len(key)] for i in range(len(data)))

def read_and_decrypt_config(file_path):
    """读取并解密配置文件"""
    if not os.path.exists(file_path):
        print(f"文件 {file_path} 不存在")
        return None

    with open(file_path, "rb") as f:
        content = f.read()

    # 验证头部
    if not content.startswith(HEADER):
        print("文件头部无效")
        return None

    # 解密数据
    encrypted_data = content[len(HEADER):]
    decrypted_data = xor_decrypt(encrypted_data, ENC_KEY)

    # 转换为字符串并返回
    try:
        return decrypted_data.decode("utf-8").strip()
    except UnicodeDecodeError:
        print("解密后的数据无法解码为 UTF-8")
        return None

if __name__ == "__main__":
    config_path = "./config.cfg"  # 假设文件在同级目录下
    decrypted_content = read_and_decrypt_config(config_path)

    if decrypted_content:
        print("解密后的内容：")
        print(decrypted_content)
    else:
        print("解密失败")